package com.netty.esc.utils;

import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @Author: Etan96
 * @CreateDate: 2022/8/27 1:26
 * @Description:
 */
@Slf4j
public class TimeUtil {

    public static final long ONE_SECOND = 1000;
    public static final long ONE_MINUTE = 60 * ONE_SECOND;

    public static final long TWO_MINUTE = 2 * ONE_MINUTE;
    public static final long THREE_MINUTE = 3 * ONE_MINUTE;
    public static final long FOUR_MINUTES = 4 * ONE_MINUTE;
    public static final long FIVE_MINUTES = 5 * ONE_MINUTE;

    /**
     * 判断是否在推送时间段内
     * @return true
     */
    public static boolean isPushPeriod(){
        try {
            String strStartTime = "2:00";
            String strEndTime = "6:00";
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
            String now = sdf.format(new Date());
            Date nowTime = sdf.parse(now);
            Date startTime = sdf.parse(strStartTime);
            Date endTime  = sdf.parse(strEndTime);
            return !isEffectiveDate(nowTime, startTime, endTime);
        }catch (Throwable throwable){
            log.error("isPushPeriod方法异常", throwable);
        }

        return true;
    }

    /**
     * 判断当前时间是否在[startTime, endTime]区间，注意三个参数的时间格式要一致
     * @param nowTime
     * @param startTime
     * @param endTime
     * @return 在时间段内返回true，不在返回false
     */
    private static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        return date.after(begin) && date.before(end);
    }
}
